package service;

//import org.hibernate.search.jpa.FullTextEntityManager;
//import org.hibernate.search.jpa.Search;

import domain.AbstractEntity;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.Search;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

public class LuceneIndexRebuilder implements ILuceneIndexRebuilder {
    private List<Class> classes;
    @PersistenceContext
    private EntityManager entityManager;
    private static final Log logger = LogFactory.getLog(LuceneIndexRebuilder.class);

    public List<Class> getClasses() {
        return classes;
    }

    public void setClasses(List<Class> classes) {
        this.classes = classes;
    }


    public void reindexEntity(AbstractEntity object) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("reindexEntity " + object);
        }
        object = entityManager.find(object.getClass(), object.getId());

        FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
        fullTextEntityManager.index(object);


    }

    public void reindexEntities() throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("reindexEntities");
        }
        FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
        for (Class aClass : classes) {
            fullTextEntityManager.purgeAll(aClass);
            List result = fullTextEntityManager.createQuery("select p from " + aClass.getSimpleName() + " p").getResultList();
            for (Object o : result) {
                fullTextEntityManager.index(o);
            }
        }
    }
}